package com.daxia.ogmall.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.daxia.ogmall.daobase.GenericDAOHibernate;
import com.daxia.ogmall.dto.AddressDTO;
import com.daxia.ogmall.model.Address;
import com.daxia.ogmall.support.Page;

@Repository
public class AddressDAO extends GenericDAOHibernate<Address> {

    public List<Address> find(AddressDTO dto, Page page) {
        StringBuilder hql = new StringBuilder();
        List<Object> paras = new ArrayList<Object>();
        hql.append("From Address n where 1 = 1 ");
        if (dto.getId() != null) {
            hql.append(" and n.id = ? ");
            paras.add(dto.getId());
        }
        if (dto.getUser() != null) {
        	if (dto.getUser().getId() != null) {
	            hql.append(" and n.user.id = ? ");
	            paras.add(dto.getUser().getId());
        	}
        }			
        if (StringUtils.isNotBlank(dto.getName())) {
            hql.append(" and n.name = ? ");
            paras.add(dto.getName());
        }		
        if (StringUtils.isNotBlank(dto.getMobile())) {
            hql.append(" and n.mobile = ? ");
            paras.add(dto.getMobile());
        }	
        hql.append(" order by n.isDefault desc ");
        return super.find(hql.toString(), paras.toArray(), page);
    }
    
    public int updateAddressDefault(Long id,Long userId) {
    	int result = 0;
    	StringBuffer setBuffer = new StringBuffer();
    	Object[] paras = new Object[]{1};
    	setBuffer.append("update Address set isDefault=false where user.id = ? ");
    	paras[0] = userId;
    	result += super.executeUpdate(setBuffer.toString(), paras);
    	StringBuffer defaultBuffer = new StringBuffer();
    	defaultBuffer.append(" update Address set isDefault=true where id = ?");
    	paras[0] = id;
    	result += super.executeUpdate(defaultBuffer.toString(), paras);
    	return result;
    }
    
    public Address findOne(AddressDTO dto) {
		Page page = new Page();
		page.setPageSize(1);
		page.setPage(1);
		
		List<Address> list = this.find(dto, page);
	    return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }
}
